package com.wuyuan.xy.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class GenerateSms {


    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${smsbao.username}")
    private String dxbUsername;

    @Value("${smsbao.password}")
    private String dxbPassword;
    @Value("${smsbao.phone1}")
    private String phone1;


   // @PostMapping("/sms/code")
   // @ResponseBody
    public void sms先不用() {

        // 保存验证码信息
      //  String uuid = IdUtils.simpleUUID();
      //  String verifyKey = Constants.SMS_CAPTCHA_CODE_KEY + uuid;
     //采用短信宝的服务
      //  int code = (int) Math.ceil(Math.random() * 9000 + 1000);
     //   String dxbUsername = "phlqphlq"; //在短信宝注册的用户名
       // String dxbPassword = "linkinpark"; //在短信宝注册的密码
        String phone = phone1;
        String content = "【WuYuan】象屿农服画地系统已经连续5次（共计50秒）没有从服务器返回信息，请检查服务或数据库是否正常。"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到
       // String content = "【WuYuan】您的验证码是56753。如非本人操作，请忽略本短信"; 这个模板是好好使的
        String httpUrl = "http://api.smsbao.com/sms";

        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(dxbUsername).append("&");
        httpArg.append("p=").append(md5(dxbPassword)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(encodeUrlString(content, "UTF-8"));
        String result = request(httpUrl, httpArg.toString());
        System.out.println(result);



        Map<String, Object> map = new HashMap<>(16);
      //  map.put("mobile", mobile);
       // map.put("code", code);


//        session.setAttribute("smsCode", map);

        logger.info(" 为 {} 发送了告警短信：", phone);

    }

    public void smsPhone(String phone) {

        // 保存验证码信息
        //  String uuid = IdUtils.simpleUUID();
        //  String verifyKey = Constants.SMS_CAPTCHA_CODE_KEY + uuid;
        //采用短信宝的服务
        //  int code = (int) Math.ceil(Math.random() * 9000 + 1000);
        //   String dxbUsername = "phlqphlq"; //在短信宝注册的用户名
        // String dxbPassword = "linkinpark"; //在短信宝注册的密码
        String content = "【WuYuan】象屿农服画地系统已经连续5次（共计50秒）没有从服务器返回信息，请检查服务或数据库是否正常。"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到
        // String content = "【WuYuan】您的验证码是56753。如非本人操作，请忽略本短信"; 这个模板是好好使的
        String httpUrl = "http://api.smsbao.com/sms";

        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(dxbUsername).append("&");
        httpArg.append("p=").append(md5(dxbPassword)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(encodeUrlString(content, "UTF-8"));
        String result = request(httpUrl, httpArg.toString());
        System.out.println(result);



        Map<String, Object> map = new HashMap<>(16);
        //  map.put("mobile", mobile);
        // map.put("code", code);


//        session.setAttribute("smsCode", map);

        logger.info(" 为 {} 发送了告警短信：", phone);

    }




    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = reader.readLine();
            if (strRead != null) {
                sbf.append(strRead);
                while ((strRead = reader.readLine()) != null) {
                    sbf.append("\n");
                    sbf.append(strRead);
                }
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String md5(String plainText) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    public static String encodeUrlString(String str, String charset) {
        String strret = null;
        if (str == null)
            return str;
        try {
            strret = java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return strret;
    }

}
